package com.zhiche.lisa.bms.service.fee.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.bms.controller.utils.ExcelController;
import com.zhiche.lisa.bms.dao.mapper.fee.FeeAssessmentMapper;
import com.zhiche.lisa.bms.dao.model.fee.FeeAssessment;
import com.zhiche.lisa.bms.dao.model.pay.PayApplyDtlAsse;
import com.zhiche.lisa.bms.pojo.dto.driver.DriverDTO;
import com.zhiche.lisa.bms.pojo.dto.fee.FeeAssessmentAndRewardDTO;
import com.zhiche.lisa.bms.pojo.dto.util.*;
import com.zhiche.lisa.bms.pojo.vo.fee.FeeAssessmentImportVO;
import com.zhiche.lisa.bms.pojo.vo.fee.FeeAssessmentVO;
import com.zhiche.lisa.bms.service.fee.FeeAssessmentService;
import com.zhiche.lisa.bms.service.pay.PayApplyDtlAsseService;
import com.zhiche.lisa.bms.service.utils.LspUtil;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 考核奖惩费用 服务实现类
 * </p>
 *
 * @author WangShuiJin
 * @since 2018-09-20
 */
@Service
public class FeeAssessmentServiceImpl extends ServiceImpl<FeeAssessmentMapper, FeeAssessment> implements FeeAssessmentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelController.class);
    @Autowired
    private OtmUtil otmUtil;

    @Autowired
    private LspUtil lspUtil;

    @Autowired
    private PayApplyDtlAsseService payApplyDtlAsseService;

    @Override
    public Page<FeeAssessment> queryFeeAssessmentPage(Page<FeeAssessment> page) {
        EntityWrapper<FeeAssessment> ew = this.queryLikeCheck(page.getCondition());
        //清空page附加条件值
        page.setCondition(Maps.newHashMap());
        page.setRecords(baseMapper.selectPage(page, ew));
        return page;
    }

    /**
     * 查询考核奖惩费用列表
     *
     * @param condition
     * @return
     */
    @Override
    public List<FeeAssessmentImportVO> queryFeeAssessmentListByCondition(Map<String, Object> condition) {
        EntityWrapper<FeeAssessment> ew = this.queryLikeCheck(condition);
        List<FeeAssessment> feeAssessmentList = baseMapper.selectList(ew);
        if (!CollectionUtils.isEmpty(feeAssessmentList)) {
            List<FeeAssessmentImportVO> voList = Lists.newArrayList();
            feeAssessmentList.forEach(feeAssess -> {
                FeeAssessmentImportVO vo = new FeeAssessmentImportVO();
                BeanUtils.copyProperties(feeAssess, vo);
                // 考核月
                if (Objects.nonNull(feeAssess.getAssessMonth())) {
                    vo.setAssessMonthStr(new DateTime(feeAssess.getAssessMonth()).toString(ToolCommonUtils.yyyyMMdd));
                }
                // 判断票内还是票外 0-票内, 1-票外
                if (Objects.nonNull(feeAssess.getInvoiceType())) {
                    if (Integer.valueOf(0).equals(feeAssess.getInvoiceType())) {
                        vo.setInvoiceTypeName("票内");
                    } else if (Integer.valueOf(1).equals(feeAssess.getInvoiceType())) {
                        vo.setInvoiceTypeName("票外");
                    }
                }
                // 是否挂起和是否发布
                if (Objects.nonNull(feeAssess.getIsHang())) {
                    if (Integer.valueOf(0).equals(feeAssess.getIsHang())) {
                        vo.setIsHangStr("未审核");
                    } else if (Integer.valueOf(1).equals(feeAssess.getIsHang())) {
                        vo.setIsHangStr("已审核");
                    }
                } else {
                    vo.setIsHangStr("未审核");
                }
                if (Objects.nonNull(feeAssess.getIsPut())) {
                    if (Integer.valueOf(0).equals(feeAssess.getIsPut())) {
                        vo.setIsPutStr("未发布");
                    } else if (Integer.valueOf(1).equals(feeAssess.getIsPut())) {
                        vo.setIsPutStr("已发布");
                    }
                } else {
                    vo.setIsPutStr("未发布");
                }
                if (Objects.nonNull(feeAssess.getCloseFlag())) {
                    if (Integer.valueOf(0).equals(feeAssess.getCloseFlag())) {
                        vo.setCloseFlagStr("未关闭");
                    } else if (Integer.valueOf(1).equals(feeAssess.getCloseFlag())) {
                        vo.setCloseFlagStr("已关闭");
                    }
                } else {
                    vo.setCloseFlagStr("未关闭");
                }
                if (!StringUtils.isEmpty(feeAssess.getFleetTeye())) {
                    if ("10".equals(feeAssess.getFleetTeye())) {
                        vo.setFleetTeye("承运商");
                    } else if ("20".equals(feeAssess.getFleetTeye())) {
                        vo.setFleetTeye("车队");
                    } else if ("30".equals(feeAssess.getFleetTeye())) {
                        vo.setFleetTeye("司机");
                    }
                }
                voList.add(vo);
            });
            return voList;
        }
        return null;
    }

    @Override
    public List<FeeAssessment> getFeeAssessmentByPayIdList(Long payId) {
        if (ObjectUtils.isEmpty(payId)) {
            return null;
        }
        List<PayApplyDtlAsse> payApplyDtlAssesList = payApplyDtlAsseService.queryPayApplyDtlAsseList(payId);
        if (CollectionUtils.isEmpty(payApplyDtlAssesList)) {
            return null;
        }
        List<Long> billIds = Lists.newArrayList();
        payApplyDtlAssesList.forEach(payApplyDtlAsses -> {
            if (!ObjectUtils.isEmpty(payApplyDtlAsses.getBilId())) {
                billIds.add(payApplyDtlAsses.getBilId());
            }
        });
        if (CollectionUtils.isEmpty(billIds)) {
            return null;
        }
        EntityWrapper ew = new EntityWrapper<>();
        ew.in("id", billIds);
        List<FeeAssessment> list = this.selectList(ew);
        return list;
    }

    @Override
    public List<FeeAssessment> getFeeAssessmentByFleetIdList(Long payeeId, Integer billProperty) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("payeeId", payeeId);
        map.put("billProperty", billProperty);
        return getAvailableFeeAssessment(map);
    }

    @Override
    public List<FeeAssessment> getAvailableFeeAssessment(Map<String, Object> stringObjectMap) {
        Object payeeId = stringObjectMap.get("payeeId");
        Object billProperty = stringObjectMap.get("billProperty");
        Object available = stringObjectMap.get("available");
        Object closeFlag = stringObjectMap.get("closeFlag");
        if (ObjectUtils.isEmpty(payeeId)) {
            throw new BaseException("收款方id,不能为空！");
        }
        if (ObjectUtils.isEmpty(billProperty)) {
            throw new BaseException("应付账单属性,不能为空！");
        }
        EntityWrapper ew = new EntityWrapper();
        //10-承运商  20-车队  30-司机
        if (Objects.deepEquals(billProperty, ExcelController.LSP_INFO_NAME)) {
            //分供方ID
            ew.eq("lsp_id", payeeId);
        } else if (Objects.deepEquals(billProperty, ExcelController.LISA_FLEET_NAME)) {
            //实际承运人id
            ew.eq("fleet_id", payeeId);
        } else if (Objects.deepEquals(billProperty, ExcelController.LISA_DRIVER_NAME)) {
            //司机手机号码
            ew.eq("driver_phone", payeeId);
        }
        if (available != null) {
            if (Objects.deepEquals(available, 0)) {
                //分供方ID
                ew.eq("is_hang", 0);
                ew.andNew().eq("balance_sum", 0).or().isNull("balance_sum");
            } else {
                ew.eq("is_hang", 1);
                ew.gt("balance_sum", 0).and().isNotNull("balance_sum");
            }
        }
        if (Objects.nonNull(closeFlag)) {
            ew.eq("close_flag", closeFlag);
        }
        return this.selectList(ew);
    }

    /**
     * 考核单挂起
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<String> blockedFeeAssessment(List<Long> ids, String token) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        return getQueryDtoList(ids, token);
        //EntityWrapper ew = new EntityWrapper();
        //ew.in("id", ids);
        //FeeAssessment feeAssessment = new FeeAssessment();
        //feeAssessment.setIsCreate(1);
        //this.update(feeAssessment, ew);
    }

    /**
     * 查询承运商和承运方
     *
     * @param ids
     * @param token
     * @return
     */
    private List<String> getQueryDtoList(List<Long> ids, String token) {
        List<LspInfoDTO> lspDtoList = Lists.newArrayList();
        List<LspFleetDTO> fleetDtoList = Lists.newArrayList();
        List<DriverDTO> driverDTOList = Lists.newArrayList();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(ids)) {
            List<FeeAssessment> assessmentList = selectBatchIds(ids);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(assessmentList)) {
                assessmentList.forEach(assess -> {
                    if (!StringUtils.isEmpty(assess.getLspName()) && assess.getLspId() == null) {
                        LspInfoDTO dto = new LspInfoDTO();
                        dto.setName(assess.getLspName());
                        lspDtoList.add(dto);
                    }
                    if (!StringUtils.isEmpty(assess.getFleetStatus()) && assess.getFleetId() == null && "20".equals(assess.getFleetTeye())) {
                        LspFleetDTO dto = new LspFleetDTO();
                        dto.setFleetName(assess.getFleetStatus());
                        fleetDtoList.add(dto);
                    }
                    if (!StringUtils.isEmpty(assess.getFleetStatus()) && assess.getFleetId() == null && "30".equals(assess.getFleetTeye())) {
                        DriverDTO dto = new DriverDTO();
                        dto.setName(assess.getFleetStatus());
                        if (!StringUtils.isEmpty(assess.getDriverPhone())) {
                            dto.setMobile(assess.getDriverPhone());
                        }
                        if (!StringUtils.isEmpty(assess.getSendCarPass())) {
                            dto.setSendCarPass(assess.getSendCarPass());
                        }
                        driverDTOList.add(dto);
                    }
                });
                // 计算
                return updateCommonAssess(lspDtoList, fleetDtoList, driverDTOList, assessmentList, token);
            }
        }
        return null;
    }

    /**
     * 判断和更新承运商和承运方
     *
     * @param lspDtoList
     * @param fleetDtoList
     * @param driverDTOList
     * @param assessmentList
     * @param token
     * @return
     */
    private List<String> updateCommonAssess(List<LspInfoDTO> lspDtoList, List<LspFleetDTO> fleetDtoList,
                                            List<DriverDTO> driverDTOList, List<FeeAssessment> assessmentList, String token) {
        List<String> msgList = Lists.newArrayList();
        Map<Long, FeeAssessment> map = Maps.newHashMap();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(lspDtoList)) {
            List<LspInfoDTO> lspInfoList = lspUtil.getLspInfoAll(lspDtoList, token);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(lspInfoList)) {
                assessmentList.stream().filter(feeAssessment -> org.apache.commons.lang3.StringUtils.isNotBlank(feeAssessment.getLspName()))
                        .forEach(feeAssessment -> {
                            lspInfoList.forEach(lspInfo -> {
                                if (feeAssessment.getLspName().equals(lspInfo.getName())) {
                                    feeAssessment.setLspId(lspInfo.getId());
                                    setMapData(map, feeAssessment);
                                } else {
                                    msgList.add(feeAssessment.getAssessCode() + ":" + feeAssessment.getLspName() + ":找不到对应数据");
                                }
                            });
                        });
            }
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(fleetDtoList)) {
            List<LspFleetDTO> fleetList = lspUtil.getFleetAll(fleetDtoList, token);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(fleetList)) {
                assessmentList.stream().filter(feeAssessment -> org.apache.commons.lang3.StringUtils.isNotBlank(feeAssessment.getFleetStatus()))
                        .forEach(feeAssessment -> {
                            fleetList.forEach(fleet -> {
                                if (feeAssessment.getFleetStatus().equals(fleet.getFleetName())) {
                                    feeAssessment.setFleetId(fleet.getId());
                                    setMapData(map, feeAssessment);
                                } else {
                                    msgList.add(feeAssessment.getAssessCode() + ":" + feeAssessment.getFleetStatus() + ":找不到对应数据");
                                }
                            });
                        });
            }

        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(driverDTOList)) {
            List<DriverDTO> driverList = lspUtil.getDriverAll(driverDTOList, token);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(driverList)) {
                assessmentList.stream().filter(feeAssessment -> org.apache.commons.lang3.StringUtils.isNotBlank(feeAssessment.getFleetStatus()))
                        .forEach(feeAssessment -> {
                            driverList.forEach(driver -> {
                                if (feeAssessment.getFleetStatus().equals(driver.getName())) {
                                    feeAssessment.setFleetId(driver.getId());
                                    setMapData(map, feeAssessment);
                                } else {
                                    msgList.add(feeAssessment.getAssessCode() + ":" + feeAssessment.getFleetStatus() + ":找不到对应数据");
                                }
                            });
                        });
            }
        }
        // 更新
        if (!map.isEmpty()) {
            List<FeeAssessment> updateAssessList = Lists.newArrayList();
            map.forEach((k, v) -> {
                assessmentList.forEach(feeAssessment -> {
                    if (!feeAssessment.getId().equals(v.getId())) {
                        msgList.add(feeAssessment.getAssessCode() + "::找不到对应数据");
                    }
                });
                v.setIsHang(1);
                v.setGmtModify(new Date());
                updateAssessList.add(v);
            });
            updateBatchById(updateAssessList);
        } else {
            List<FeeAssessment> updateAssessList = Lists.newArrayList();
            assessmentList.forEach(assess -> {
                if (assess.getLspId() == null || assess.getFleetId() == null) {
                    msgList.add("错误信息:" + assess.getAssessCode() + ":找不到分供方或承运方对应数据");
                } else {
                    assess.setIsHang(1);
                    assess.setGmtModify(new Date());
                    updateAssessList.add(assess);
                }
            });
            if (!CollectionUtils.isEmpty(updateAssessList)) {
                updateBatchById(updateAssessList);
            }
        }
        return msgList;
    }

    private void setMapData(Map<Long, FeeAssessment> map, FeeAssessment feeAssessment) {
        if (map.get(feeAssessment.getId()) == null) {
            map.put(feeAssessment.getId(), feeAssessment);
        }
    }

    /**
     * 考核单发布
     *
     * @param feeAssessmentList
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void publishFeeAssessment(List<FeeAssessment> feeAssessmentList) {
        if (CollectionUtils.isEmpty(feeAssessmentList)) {
            return;
        }
        List<Long> ids = Lists.newArrayList();
        List<SynchroAssessmentDTO> synchroAssessmentList = Lists.newArrayList();
        feeAssessmentList.forEach(feeAssessment -> {
            SynchroAssessmentDTO synchroAssessmentDTO = new SynchroAssessmentDTO();
            synchroAssessmentDTO.setArap("AP");
            synchroAssessmentDTO.setAssessCode(feeAssessment.getAssessCode());
            synchroAssessmentDTO.setAssessDept(feeAssessment.getAssessDep());
            synchroAssessmentDTO.setAssessMoney(feeAssessment.getAssessSum());
            synchroAssessmentDTO.setAssessName(feeAssessment.getAssessItem());
            synchroAssessmentDTO.setAssessReason(feeAssessment.getAssessCause());
            synchroAssessmentDTO.setCreateTime(feeAssessment.getGmtCreate());
            synchroAssessmentDTO.setDiscountMoney(feeAssessment.getMitigateSum());
            synchroAssessmentDTO.setDiscountReason(feeAssessment.getMitigateCause());
            synchroAssessmentDTO.setShipperId(feeAssessment.getLspId());
            synchroAssessmentDTO.setShipperName(feeAssessment.getLspName());
            synchroAssessmentDTO.setTotalMoney(feeAssessment.getAmount());
            // 类型
            synchroAssessmentDTO.setInvoiceStatus(feeAssessment.getInvoiceType());
            if (!ObjectUtils.isEmpty(synchroAssessmentDTO)) {
                synchroAssessmentList.add(synchroAssessmentDTO);
            }
            if (!ObjectUtils.isEmpty(feeAssessment.getId())) {
                ids.add(feeAssessment.getId());
            }
        });
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseException("考核单发布失败，没有找到考核单！");
        }
        EntityWrapper ew = new EntityWrapper();
        ew.in("id", ids);

        //向主系统同步考核单
        if (!CollectionUtils.isEmpty(synchroAssessmentList)) {

            BmsServiceResult otmSynchroAssessment = otmUtil.synchroAssessment(synchroAssessmentList);
            if (!otmSynchroAssessment.isSuccess()) {
                throw new BaseException("考核发布失败");
            }
        }
        JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
        // 更新标识
        if (!CollectionUtils.isEmpty(feeAssessmentList)) {
            List<FeeAssessment> updateList = Lists.newArrayList();
            feeAssessmentList.stream().filter(feeAssess -> feeAssess.getId() != null).forEach(feeAssess -> {
                FeeAssessment feeAssessmentMode = new FeeAssessment();
                feeAssessmentMode.setIsPut(1);//考核发布成功标识
                feeAssessmentMode.setId(feeAssess.getId());
                feeAssessmentMode.setPutUsername(account.getUsername());
                updateList.add(feeAssessmentMode);
            });

            if (!CollectionUtils.isEmpty(updateList)) {
                this.updateBatchById(updateList);
            }
        }


        //List<FeeAssessment> resultFeeAssessmentList = JSONArray.parseArray(otmSynchroAssessment.getData(), FeeAssessment.class);
        //feeAssessmentList.forEach(feeAssessment -> {
        //    resultFeeAssessmentList.forEach(resultFeeAssessment -> {
        //        if (feeAssessment.getAssessCode().equals(resultFeeAssessment.getAssessCode())) {
        //            feeAssessmentMode.setPerformSum(resultFeeAssessment.getPerformSum());
        //            this.update(feeAssessmentMode,ew);
        //        }
        //    });
        //});
    }

    /**
     * 删除
     *
     * @param assessIdList
     */
    @Override
    public void deleteFeeAssessment(List<Long> assessIdList) {
        if (CollectionUtils.isEmpty(assessIdList)) {
            return;
        }
        this.deleteBatchIds(assessIdList);
    }

    /**
     * 插入
     *
     * @param feeAssessmentList
     */
    @Override
    public void insertFeeAssessment(List<FeeAssessment> feeAssessmentList) {
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(feeAssessmentList)) {
            this.insertBatch(feeAssessmentList);
        }
    }

    /**
     * 模糊查询条件
     *
     * @param condition 模糊查询字段
     * @return
     */
    private EntityWrapper<FeeAssessment> queryLikeCheck(Map<String, Object> condition) {
        LOGGER.info("/FeeAssessmentServiceImpl.queryLikeCheck INFO: params : {} " + condition);
        EntityWrapper<FeeAssessment> ew = new EntityWrapper<>();
        ew.orderBy("gmt_create desc, id desc");
        if (!CollectionUtils.isEmpty(condition)) {
            //遍历条件
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!Strings.isNullOrEmpty(entry.getKey())) {
                    // LOGGER.info("queryLikeCheck enter foreach INFO: key :" + entry.getKey() + ",Value :" + entry.getValue());
                    //考核单号
                    if ("assessCode".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.eq("assess_code", entry.getValue());
                    }
                    //考核月或承运商
                    if ("assessMonthOrFleetName".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.andNew().like("assess_month", String.valueOf(entry.getValue())).
                                or().like("fleet_status", String.valueOf(entry.getValue()));
                    }
                    // 承运类型
                    if ("fleetTeye".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.eq("fleet_teye", entry.getValue());
                    }
                    // 承运人
                    if ("fleetStatus".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.like("fleet_status", entry.getValue().toString());
                    }
                    // 承运类型
                    if ("lspName".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.like("lsp_name", entry.getValue().toString());
                    }
                    // 是否发布
                    if ("isPut".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.eq("is_put", entry.getValue());
                    }
                    // 是否挂起
                    if ("isHang".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.eq("is_hang", entry.getValue());
                    }
                    // 考核月
                    if ("assessMonth".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM");
                        Date firstDayOfMonth = ToolCommonUtils.getFirstDayOfMonth(format.parseDateTime(entry.getValue().toString()).toDate());
                        ew.eq("assess_month", firstDayOfMonth);
                    }
                    // 创建人
                    if ("createUsername".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.like("create_username", entry.getValue().toString());
                    }
                    // 考核部门
                    if ("assessDep".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.like("assess_dep", entry.getValue().toString());
                    }
                    // 创建时间
                    if ("createTimeStart".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.ge("gmt_create", entry.getValue());
                    }
                    // 创建时间
                    if ("createTimeEnd".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.le("gmt_create", entry.getValue());
                    }

                    // 考核月
                    if ("assessMonthStart".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        Date assessMonthStart = ToolCommonUtils.getDateByStr(entry.getValue().toString(), ToolCommonUtils.yyyyMM);
                        ew.ge("assess_month", ToolCommonUtils.getFirstDayOfMonth(assessMonthStart));
                    }
                    // 考核月
                    if ("assessMonthEnd".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        Date assessMonthEnd = ToolCommonUtils.getDateByStr(entry.getValue().toString(), ToolCommonUtils.yyyyMM);
                        ew.le("assess_month", ToolCommonUtils.getLastDayOfMonth(assessMonthEnd));
                    }
                    // 关闭状态
                    if ("closeFlag".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                        ew.eq("close_flag", entry.getValue());
                    }
                }
            }
        }
        // LOGGER.info("queryLikeCheck result INFO: params : {} " + ew.toString());
        return ew;
    }

    /**
     * 根据code值获取对应的考核信息
     *
     * @param code
     * @return
     */
    @Override
    public List<FeeAssessment> selectFeeAssessmentListByCodes(List<String> code) {
        EntityWrapper<FeeAssessment> feeAssessmentEntityWrapper = new EntityWrapper<>();
        feeAssessmentEntityWrapper.in("assess_code", code);
        return this.selectList(feeAssessmentEntityWrapper);
    }

    @Override
    public List<FeeAssessment> getFeeAssessmentListByIds(List<Long> ids) {
        EntityWrapper<FeeAssessment> ew = new EntityWrapper<>();
        ew.in("id", ids);
        return this.selectList(ew);
    }

    /**
     * 根据应付账款ID和多个考核奖惩ID,得到考核奖惩信息
     *
     * @param feePayableId
     * @param ids
     * @return
     */
    @Override
    public List<Long> getFeeAssessmentSumByFeepIdAndIds(Long feePayableId, List<Long> ids) {
        return baseMapper.getFeeAssessmentSumByFeepIdAndIds(feePayableId, ids);
    }

    /**
     * 获取支付申请对应的考核单
     *
     * @param payId
     * @return
     */
    @Override
    public List<FeeAssessmentVO> getFeeAssessmentVoListByPayId(Long payId) {
        if (payId != null) {
            // List<PayApplyDtlAsse> applyDtlAsseList = payApplyDtlAsseService.queryPayApplyDtlAsseList(payId);
            // if (applyDtlAsseList.isEmpty()){ return null;}
            // List<Long> assessIdList = Lists.newArrayList();
            // applyDtlAsseList.forEach(payApplyDtlAsse -> {
            //     if (!ObjectUtils.isEmpty(payApplyDtlAsse.getBilId())) {
            //         assessIdList.add(payApplyDtlAsse.getBilId());
            //     }
            // });
            // if (assessIdList.isEmpty()){ return null;}
            // EntityWrapper ew = new EntityWrapper<>();
            // ew.in("id", assessIdList);
            // return this.selectList(ew);
            return baseMapper.getFeeAssessmentVoListByPayApplyId(payId);
        }
        return null;
    }

    /**
     * 根据code值获取对应的考核信息 - 无token
     *
     * @param code
     * @return
     */
    @Override
    public List<FeeAssessment> selectFeeAssessmentListByCodesNoTenant(Set<String> code) {
        EntityWrapper<FeeAssessment> feeAssessmentEntityWrapper = new EntityWrapper<>();
        feeAssessmentEntityWrapper.in("assess_code", code);
        return baseMapper.selectListNoTenant(feeAssessmentEntityWrapper);
    }

    /**
     * 关闭考核单
     *
     * @param idList
     * @param reason
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<String> closeAssessment(List<Long> idList, String reason) {

        List<String> resultMessageList = Lists.newArrayList();

        List<FeeAssessment> assessmentList = this.selectBatchIds(idList);
        List<FeeAssessment> closeBmsDataList = Lists.newArrayList();
        List<FeeAssessment> updateBmsDataList = Lists.newArrayList();

        List<FeeAssessment> notPutAssessmentList = Lists.newArrayList();

        if (!CollectionUtils.isEmpty(assessmentList)) {
            assessmentList
                    .stream()
                    .forEach(assessment -> {
                        if (Objects.nonNull(assessment.getIsPut()) && Integer.valueOf(1).equals(assessment.getIsPut())) {
                            // 判断执行金额
                            if (Objects.isNull(assessment.getPerformSum())) {
                                // 执行金额 = 0 是关闭
                                closeBmsDataList.add(assessment);
                            } else {
                                if (BigDecimal.ZERO.compareTo(assessment.getPerformSum()) == 0 && BigDecimal.ZERO.compareTo(assessment.getBmsSum()) == 0) {
                                    // 运力执行金额和bms执行金额都 = 0 走更新接口
                                    closeBmsDataList.add(assessment);
                                } else {
                                    // 执行金额 != 0 走关闭
                                    updateBmsDataList.add(assessment);
                                }
                            }
                        } else {
                            notPutAssessmentList.add(assessment);
                        }
                    });
        }
        List<BmsServiceData> resulDataLis = Lists.newArrayList();

        //TODO 调用bms接口
        if (!CollectionUtils.isEmpty(closeBmsDataList)) {
            // 推送bms
            List<BmsServiceData> closeServiceDataList = this.bmsCloseAssessment(closeBmsDataList);
            if (!CollectionUtils.isEmpty(closeServiceDataList)) {
                resulDataLis.addAll(closeServiceDataList);
            }
        }
        if (!CollectionUtils.isEmpty(updateBmsDataList)) {
            // 推送bms
            List<BmsServiceData> updateServiceDataList = this.bmsUpdateAssessment(updateBmsDataList);
            if (!CollectionUtils.isEmpty(updateServiceDataList)) {
                resulDataLis.addAll(updateServiceDataList);
            }
        }
        if (!CollectionUtils.isEmpty(resulDataLis)) {
            List<String> codeList = Lists.newArrayList();
            resulDataLis.forEach(resultData -> {
                if (resultData.isDealFlag()) {
                    codeList.add(resultData.getAssessCode());
                } else {
                    resultMessageList.add("单号:" + resultData.getAssessCode() + ":" + resultData.getDealMessage());
                }
            });
            EntityWrapper<FeeAssessment> ew = new EntityWrapper<>();
            ew.in("assess_code", codeList);
            FeeAssessment updateAssessement = new FeeAssessment();
            updateAssessement.setCloseFlag(1);
            updateAssessement.setCloseReason(reason);
            // 更新数据
            this.update(updateAssessement, ew);
        }
        if (!CollectionUtils.isEmpty(notPutAssessmentList)) {
            notPutAssessmentList.forEach(updateAssessement -> {
                updateAssessement.setCloseFlag(1);
                updateAssessement.setCloseReason(reason);
            });
            this.updateBatchById(notPutAssessmentList);
        }
        return resultMessageList;
    }

    /**
     * 推送bms更新接口
     *
     * @param updateBmsDataList
     */
    private List<BmsServiceData> bmsUpdateAssessment(List<FeeAssessment> updateBmsDataList) {
        List<FeeAssessmentAndRewardDTO> dtoList = Lists.newArrayList();
        updateBmsDataList.forEach(bmsData -> {
            FeeAssessmentAndRewardDTO feeAssessmentAndRewardDTO = otmUtil.packageParamJson(bmsData.getAssessCode(),
                    0, bmsData.getPerformSum(), bmsData.getBmsSum());
            dtoList.add(feeAssessmentAndRewardDTO);
        });
        BmsServiceResult bmsServiceResult = otmUtil.assessmentAndRewardUpdate(dtoList);
        if (Objects.isNull(bmsServiceResult)) {
            throw new BaseException("bms系统没有返回数据");
        }
        if (!bmsServiceResult.isSuccess()) {
            throw new BaseException(bmsServiceResult.getMessage());
        }
        if (!StringUtils.isEmpty(bmsServiceResult.getData())) {
            return JSONArray.parseArray(bmsServiceResult.getData(), BmsServiceData.class);
        }
        return null;
    }

    /**
     * bms关闭
     *
     * @param closeBmsDataList
     */
    private List<BmsServiceData> bmsCloseAssessment(List<FeeAssessment> closeBmsDataList) {
        List<AssessRedDTO> dtoList = Lists.newArrayList();
        closeBmsDataList.forEach(bmsData -> {
            AssessRedDTO assessRedDTO = new AssessRedDTO();
            assessRedDTO.setDelFlag(1);
            assessRedDTO.setAssessCode(bmsData.getAssessCode());
            dtoList.add(assessRedDTO);
        });
        if (!CollectionUtils.isEmpty(dtoList)) {
            BmsServiceResult bmsServiceResult = otmUtil.delFlagURL(dtoList);
            if (bmsServiceResult == null) {
                throw new BaseException("同步BMS未响应");
            }
            if (!bmsServiceResult.isSuccess()) {
                throw new BaseException("同步BMS：" + bmsServiceResult.getMessage());
            }
            if (!StringUtils.isEmpty(bmsServiceResult.getData())) {
                return JSONArray.parseArray(bmsServiceResult.getData(), BmsServiceData.class);
            }
        }
        return null;
    }
}
